#项目主入口
from fastapi import FastAPI,Depends
from pydantic import BaseModel
import uvicorn
from fastapi.middleware.cors import CORSMiddleware #跨域
from extend.db import Engine,Base
from sqlalchemy.orm import Session
from extend.get_db import init_db
from utils.get_md5_data import get_md5_pwd
from models.user.user_operation import get_user_by_username_and_pwd,get_user_by_id
from fastapi.responses import JSONResponse
from datetime import timedelta
from utils import token
#导入其他路由
from apps.user.user_list import router as user_router
from apps.jdnode.jdlist import router as jdnode_router
#日志
from fastapi.templating import Jinja2Templates

app = FastAPI(
     title='D哥',
     description='D哥'

)

# 添加模板支持
# templates = Jinja2Templates(directory="templates")

# # 日志记录中间件
# @app.middleware("http")
# async def log_middleware(request: Request, call_next):
#     response: Response = await call_next(request)
#     # 记录日志
#     # print(f"{request.method} {request.url} -> {response.status_code} {response.headers}")
#     file = open("./logs/fastapi_info.log", "a")
#     content = (f"{request.method} {request.url} -> {response.status_code} {response.headers}")
#     file.write(content + "\n")
#     file.close()
#     return response


#注册分路由
app.include_router(user_router)
app.include_router(jdnode_router)

#token过期时间 60分中
ACCESS_TOKEN_EXPIRE_MINUTES = 50


app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],          # 允许所有的服务跨域访问
    allow_credentials=True,
    allow_methods=["*"],          # 允许所有的方法，也可以指定post，get等
    allow_headers=["*"],
)





#创建数据库表解构
#创建表解构
Base.metadata.create_all(bind=Engine)



#登录接口传参类型
class User_type(BaseModel):
    username: str
    password: str



#登录=========================================================
@app.post('/login')
def Login(user:User_type,db:Session = Depends(init_db)): #前端传入账号密码 username 和 password

     #1,获取用户信息
     username = user.username
     pwd = user.password
     jm_pwd = get_md5_pwd(pwd) #密码加密
     #数据库库校验
     user = get_user_by_username_and_pwd(db,username,jm_pwd)
     # if user.state == 0: return JSONResponse(content={'code':500,'msg':'用户禁止访问'})

     if user:
         if user.state == 0: return JSONResponse(content={'code':500,'msg':'用户禁止访问'})
         #处理时间
         expire_time = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)  # 时间

         ret_token = token.create_token({"sub":str(user.id)},expire_time)
         count = {'code':200,'msg':'登录成功','token':ret_token}
         return JSONResponse(content=count)
     else:
         count = {'code':500,'msg':'用户或者密码错误'}
         return JSONResponse(content=count)

#首页数据返回(需要校验token)==================================================
@app.get('/index')
def index(id:str = Depends(token.pass_token),db:Session = Depends(init_db)):

    #校验token 根据token解析id查询数据库
    user = get_user_by_id(db,int(id))
    user_info = {
             'id': user.id,
             'username': user.username,
             'avatar': user.avatar,
             'create_time':user.create_time,
             'dep_id': user.dep_id,
             'state':user.state
    }
    return user_info



if __name__ == '__main__':
   uvicorn.run(app='main:app',reload=True,host='127.0.0.1',port=8080)